import { StatusBar } from 'expo-status-bar';
import {
  StyleSheet, Text, View, FlatList
} from 'react-native';
import react, { useState, useEffect } from 'react';

let page = 1;
let now = 0;
export default function App() {
  const [topics, setTopics] = useState([])
  const [refresh, setRefresh] = useState(false)
  const getTopics = (page, cb) => {
    fetch('https://cnodejs.org/api/v1/topics?page=' + page)
      .then(res => res.json())
      .then(res => {
        if (page == 1) {
          setTopics(res.data);
        } else {
          setTopics([...topics, ...res.data]);
          // cb有就执行，没有就不执行
        }
        cb && cb(res.data);
      })
  }
  useEffect(() => {
    getTopics(1, (data) => setTopics(data))
  }, [])
  return (
    <View style={styles.container}>

      {/* Flatlist本身可以滚动外面就不用要ScrowView了 */}
      <FlatList
        onEndReachedThreshold={0}
        data={topics}
        renderItem={({ item }) => <Text
          numberOfLines={1}
          style={styles.text}>{item.title}</Text>}
        keyExtractor={item => item.id}
        onRefresh={() => {
          setRefresh(true);
          //保证得到了以后进行更新状态，先getTopics再setRefresh
          getTopics(1, (data) => { setTopics(data); setRefresh(false) });
        }}
        refreshing={refresh}
        onEndReached={() => {
          page++;
          getTopics(page, (data) => { setTopics([...topics, ...data]) });
          console.log(page);
        }}
      />
    </View>
  );
}
const styles = StyleSheet.create({
  container: {

  },
  text: {
    fontSize: 15,
    marginTop: 15,
    width:'70%'
  },
  font: {
    color: '#fca',
    fontSize: 32
  }
});
